//
//  UIViewExtension.swift
//  ShareVipForBusiness
//
//  Created by OzIntel on 2017/11/7.
//  Copyright © 2017年 zev. All rights reserved.
//

import UIKit
import Foundation

class LoadingView: UIView {

    public var lineWidth: Int = 2  //线的宽度  默认为2

    public var lineColor: UIColor = blueColor //线的颜色  默认是红色

    fileprivate var timer: Timer?

    fileprivate var originStart: CGFloat = CGFloat(Double.pi / 2 * 3)  //开始位置

    fileprivate var originEnd: CGFloat = CGFloat(Double.pi / 2 * 3 )   //结束位置  都是顶部

    fileprivate var isDraw: Bool = true
    
    deinit {
        timer?.invalidate()
        timer = nil
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.layer.cornerRadius = 10 //圆角  纯属好看
        self.layer.masksToBounds = true
        self.timer = Timer.scheduledTimer(timeInterval: 0.03, target: self, selector: #selector(LoadingView.updateLoading), userInfo: nil, repeats: true)  //创建计时器
        RunLoop.main.add(self.timer!, forMode: RunLoop.Mode.default)//计时器需要加入到RunLoop中：RunLoop的目的是让你的线程在有工作的时候忙碌，没有工作的时候休眠
        self.timer?.fire()
    }

    @objc func updateLoading () {
        if (self.originEnd == CGFloat(Double.pi / 2 * 3) && isDraw) {//从无到有的过程
            self.originStart += CGFloat(Double.pi / 30)
            if (self.originStart >= CGFloat(Double.pi / 2 * 3 + 2 * Double.pi)) {
                self.originStart = CGFloat(Double.pi / 2 * 3 + 2 * Double.pi)
                self.isDraw = false
                self.setNeedsDisplay() //调用 draw(_ rect: CGRect) 方法
                return
            }
        }

        if (self.originStart == CGFloat(Double.pi / 2 * 3 + 2 * Double.pi) && !self.isDraw) { //从有到无
            self.originEnd += CGFloat(Double.pi / 30)
            if (self.originEnd >= CGFloat(Double.pi / 2 * 3 + 2 * Double.pi)) {
                self.isDraw = true
                self.originStart = CGFloat(Double.pi / 2 * 3)
                self.originEnd = CGFloat(Double.pi / 2 * 3)
                self.setNeedsDisplay() //调用 draw(_ rect: CGRect) 方法
                return
            }
        }
        self.setNeedsDisplay() //调用 draw(_ rect: CGRect) 方法
    }

    override func draw(_ rect: CGRect) {
        let context = UIGraphicsGetCurrentContext() //获取上下文
        let center: CGPoint = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2) // 确定圆心
        let radius = min(self.frame.size.width, self.frame.size.height) / 2 - CGFloat(self.lineWidth) - 20; //半径
        let path: UIBezierPath = UIBezierPath.init(arcCenter: center, radius: radius, startAngle: self.originStart, endAngle: self.originEnd, clockwise: false) //弧的路径
        context?.addPath(path.cgPath) //将路径、宽度、颜色添加到上下文
        context?.setLineWidth(CGFloat(self.lineWidth)) //
        context?.setStrokeColor(self.lineColor.cgColor) //
        context?.strokePath() //显示弧
    }


    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension UIView{
    func loadingPage(){//页面loading
        let emptyView = self.viewWithTag(9997)
        emptyView?.removeFromSuperview()
        var view = self.viewWithTag(997)
        view?.removeFromSuperview()
        view = UIView.init(frame: self.bounds)
        view?.backgroundColor = UIColor.white
        view?.tag = 997
        self.addSubview(view!)
        let _containerLayer = CAReplicatorLayer()
        _containerLayer.masksToBounds = true;
        _containerLayer.instanceCount = 12;
        _containerLayer.instanceDelay = 0.9 / 12.0;
        _containerLayer.instanceTransform = CATransform3DMakeRotation((CGFloat(Double.pi * ((360 / 12.0)) / 180.0)), 0, 0, 1);
        view?.layer.addSublayer(_containerLayer)
        _containerLayer.frame = CGRect.init(x: (view!.frame.size.width-80)/2, y: (view!.frame.size.height-80)/2, width: 80, height: 80)
        
        let subLayer = CALayer();
        subLayer.backgroundColor = yellowColor.cgColor;
        subLayer.frame = CGRect.init(x: (80 - 12) / 2, y: 0, width: 12, height: 12)
        subLayer.cornerRadius = 12 / 2;
        subLayer.transform = CATransform3DMakeScale(0, 0, 0);
        _containerLayer.addSublayer(subLayer)
        let animation = CABasicAnimation.init(keyPath: "transform.scale")
        animation.fromValue = 1;
        animation.toValue = 0.1;
        animation.repeatCount = Float(Int.max);
        animation.duration = 0.9;
        subLayer.add(animation, forKey: nil)
    }
    
    @objc func loading(){//操作loading
        let emptyView = self.viewWithTag(9997)
        emptyView?.removeFromSuperview()
        var view = self.viewWithTag(997)
        view?.removeFromSuperview()
        view = UIView.init(frame: self.bounds)
        view?.backgroundColor = UIColor.clear
        view?.tag = 997
        self.addSubview(view!)
        let loadingView: LoadingView = LoadingView(frame: CGRect(x: view!.frame.size.width/2-50, y: view!.frame.size.height/2-50, width: 100, height: 100))
        loadingView.backgroundColor = UIColor.init(white: 230/255.0, alpha: 1.0)
        view?.addSubview(loadingView)
    }
    
    @objc func loading(msg:String){//操作loading
        let emptyView = self.viewWithTag(9997)
        emptyView?.removeFromSuperview()
        let loadingLabel = self.viewWithTag(1001) as? UILabel
        if loadingLabel != nil{
            loadingLabel?.text = msg
            return
        }
        var view = self.viewWithTag(997)
        view?.removeFromSuperview()
        view = UIView.init(frame: self.bounds)
        view?.backgroundColor = UIColor.clear
        view?.tag = 997
        self.addSubview(view!)
        
        let bgView = UIView.init(frame: CGRect.init(x: (view!.frame.size.width-140)/2, y: (view!.frame.size.height-120)/2, width: 140, height: 120))
        bgView.layer.cornerRadius = 10
        bgView.layer.masksToBounds = true
        bgView.backgroundColor = UIColor.init(white: 230/255.0, alpha: 1.0)
        view?.addSubview(bgView)
        
        let loadingView: LoadingView = LoadingView(frame: CGRect(x: 20, y: 0, width: 100, height: 100))
        loadingView.backgroundColor = UIColor.clear
        loadingView.tag = 998
        bgView.addSubview(loadingView)
        
        let label = UILabel()
        label.textColor = UIColor.gray
        label.font = UIFont.systemFont(ofSize: 12)
        label.text = msg
        label.tag = 1001
        label.frame = CGRect.init(x: 10, y: 95, width: 120, height: 20)
        label.textAlignment = .center
        bgView.addSubview(label)
    }
    
    @objc func setLoadingLabel(msg:String){
        let view = self.viewWithTag(997)
        if view != nil{
            let label = view?.viewWithTag(1001) as? UILabel
            if label != nil{
                label?.text = msg
            }
        }
    }
    
    @objc func loadComplete(){
        let loadingView : LoadingView? = self.viewWithTag(998) as? LoadingView
        loadingView?.timer?.invalidate()
        loadingView?.timer = nil
        loadingView?.removeFromSuperview()
        let emptyView = self.viewWithTag(9997)
        emptyView?.removeFromSuperview()
        let view = self.viewWithTag(997)
        view?.removeFromSuperview()
    }
    
    func showNetworkError() -> NetworkErrorView{
        var view = self.viewWithTag(997)
        view?.removeFromSuperview()
        view = NetworkErrorView()
        view?.frame = self.bounds
        self.addSubview(view!)
        return view as! NetworkErrorView
    }
    
    @objc func showEmptyView(y:CGFloat,image:String = "pic_kong_normal",text:String = "暂无数据"){
        var view = self.viewWithTag(9997)
        view?.removeFromSuperview()
        view = UIView.init(frame: CGRect.init(x: (self.frame.size.width - 200)/2, y: (self.frame.size.height-130)/2+y, width: 200, height: 115))
        view?.isUserInteractionEnabled = false
        view?.tag = 9997
        let imageView = UIImageView.init(image: UIImage.init(named: image))
        imageView.frame = CGRect.init(x: 20, y: 0, width: 160, height: 88)
        view?.addSubview(imageView)
        let label = UILabel.init(frame: CGRect.init(x: 0, y: 98, width: 200, height: 17))
        label.textColor = UIColor.withHex(hexString: "999999")
        label.font = UIFont.systemFont(ofSize: 12)
        label.textAlignment = .center
        label.text = text
        view?.addSubview(label)
        self.addSubview(view!)
    }
    
    @objc func showInfo(text:String){
        let view : UILabel? = self.viewWithTag(9998) as? UILabel
        if view != nil{
            view?.text = " \(text) "
            return
        }
        let label = UILabel.init(frame: CGRect.zero)
        label.textColor = UIColor.white
        label.font = UIFont.systemFont(ofSize: 12)
        label.textAlignment = .center
        label.backgroundColor = UIColor.init(white: 0, alpha: 0.4)
        label.text = " \(text) "
        label.isUserInteractionEnabled = false
        label.layer.cornerRadius = 4
        label.tag = 9998
        label.layer.masksToBounds = true
        self.addSubview(label)
        label.snp.makeConstraints { (make) in
            make.right.equalTo(self.snp.right).offset(-15)
            make.top.equalTo(self).offset(statusbarHeight + 44 + 10)
            make.height.equalTo(22)
        }
    }
    
    @objc func hiddenInfo(){
        let view = self.viewWithTag(9998)
        view?.removeFromSuperview()
    }
    
    @objc func backButtonClicked(){
        UIViewController.currentViewController()?.navigationController?.popViewController(animated: true)
    }
}

extension UIViewController {
    @objc class func currentViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let nav = base as? UINavigationController {
            return currentViewController(base: nav.visibleViewController)
        }
        if let tab = base as? ZWTabBarController {
            return currentViewController(base: tab.selectedViewController)
        }
        if let presented = base?.presentedViewController {
            return currentViewController(base: presented)
        }
        return base
    }
}

